const video = document.getElementById('video')
let capture = document.getElementById('capture')
let canvas;
let context;

Promise.all([
  faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
  faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
  faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
  faceapi.nets.faceExpressionNet.loadFromUri('/models')
]).then(startVideo)

function startVideo() {
  navigator.getUserMedia(
    { video: {} },
    stream => video.srcObject = stream,
    err => console.error(err)
  )
}

video.addEventListener('play', () => {
  canvas = faceapi.createCanvasFromMedia(video)
  context = canvas.getContext('2d');
  document.body.append(canvas)
  const displaySize = { width: video.width, height: video.height }
  faceapi.matchDimensions(canvas, displaySize)
  setInterval(async () => {
    const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions()
    const resizedDetections = faceapi.resizeResults(detections, displaySize)
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
    faceapi.draw.drawDetections(canvas, resizedDetections)
    faceapi.draw.drawFaceLandmarks(canvas, resizedDetections)
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
  }, 100)
})

capture.addEventListener('click', function () {
  context.drawImage(video, 0, 0, 480, 320);
  // 获取图片base64链接
  var image = canvas.toDataURL('image/png');
  // 定义一个img
  var img = document.getElementById("img");
  //设置属性和src
  //img.id = "imgBoxxx";
  img.src = image;
  //将图片添加到页面中
  //document.body.appendChild(img);
  function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    file = new File([u8arr], filename, {type: mime});
    return new File([u8arr], filename, {type: mime});
  }
  console.log(dataURLtoFile(image, 'aa.png'));
})